package com.soma.game.service.impl;

import com.soma.game.entity.User;
import com.soma.game.entity.UserExample;
import com.soma.game.enums.BooleanStatus;
import com.soma.game.mapper.UserMapper;
import com.soma.game.model.SomaUser;
import com.soma.game.service.UserService;
import com.soma.game.service.soma.SomaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl extends BaseServiceImpl<UserMapper, User, UserExample>  implements UserService {


    @Resource
    private SomaService somaService;

    @Override
    public User getByUid(Long uid) {
        UserExample example = new UserExample();
        example.createCriteria().andActiveFlgEqualTo(BooleanStatus.Y).andUidEqualTo(uid);
        List<User> users = selectByExample(example);
        //如果用户是空，向soma请求用户信息保存到本地
        if(CollectionUtils.isEmpty(users)){
            SomaUser somaUser = somaService.getUser(uid);

            //再次检查
            UserExample example1 = new UserExample();
            example1.createCriteria().andActiveFlgEqualTo(BooleanStatus.Y).andUidEqualTo(uid);
            List<User> users1 = selectByExample(example1);
            if(!CollectionUtils.isEmpty(users1)){
                return users1.stream().findFirst().get();
            }

            if(somaUser != null){
                User user = new User();
                user.setHeadImg(somaUser.getAvatar());
                user.setNickName(somaUser.getName());
                user.setUid(somaUser.getId());
                save(user);
                return user;
            }
        }
        return users.stream().findFirst().orElse(null);
    }

    @Override
    public void updateBySomaUser(SomaUser somaUser) {
        User user = new User();
        user.setNickName(somaUser.getName());
        user.setHeadImg(somaUser.getAvatar());

        UserExample example = new UserExample();
        example.createCriteria().andUidEqualTo(somaUser.getId());

        updateByExampleSelective(user, example);
    }
}